package pers.qianyu.month_202011.date_20201118;

import java.util.*;

/**
 * 1. 两数之和
 * https://leetcode-cn.com/problems/two-sum/
 *
 * @author mizzle rain
 * @date 2020-11-18 15:29
 */
public class TwoSum2 {
    /**
     * twoSum问题通解，返回元素内容，并且无重复
     */
    public List<List<Integer>> twoSum(int[] nums, int target) {
        Arrays.sort(nums);
        ArrayList<List<Integer>> res = new ArrayList<>();
        int left = 0, right = nums.length - 1;
        while (left < right) {
            int leftNum = nums[left];
            int rightNum = nums[right];
            int sum = leftNum + rightNum;

            if (sum > target) {
                while (left < right && rightNum == nums[right]) {
                    right--;
                }
            } else if (sum < target) {
                while (left < right && leftNum == nums[left]) {
                    left++;
                }
            } else {
                res.add(new ArrayList<>(Arrays.asList(leftNum, rightNum)));
                while (left < right && leftNum == nums[left]) {
                    left++;
                }
                while (left < right && rightNum == nums[right]) {
                    right--;
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Random random = new Random();
        int len = random.nextInt(100);
        int[] arr = new int[len];
        for (int i = 0; i < len; i++) {
            arr[i] = random.nextInt(100);
        }
        int target = random.nextInt(200);
        System.out.println("arr = " + Arrays.toString(arr));
        System.out.println("target = " + target);
        List<List<Integer>> result = new TwoSum2().twoSum(arr, target);
        System.out.println("result = " + result);
    }
}
